//
//  STStoryCommentView.swift
//  Story
//
//  Created by 汤泽川 on 2019/4/24.
//  Copyright © 2019 汤泽川. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import PKHUD

protocol STStoryCommentViewDelegate : NSObjectProtocol {
    func didClickComment(model : STCommentInfo)
    func didClickUserAvatar(authorName : String)
}

class STStoryCommentView: UIView, STStoryCommentViewDelegate, UITextFieldDelegate {
    func didClickUserAvatar(authorName : String) {
        self.delegate?.didClickUserAvatar(authorName: authorName)
    }
    private let tableView = UITableView()
    private let viewModel : STStoryCommentViewModel
    public weak var delegate : STStoryCommentViewDelegate?
    private let disposeBag = DisposeBag()
    private let bottomView = UIView()
    private let commentInputView = UITextField()
    private let alphaButton = UIButton()
    private var lastComment : String? = nil
    
    init(viewModel : STStoryCommentViewModel) {
        self.viewModel = viewModel
        super.init(frame: CGRect.zero)
        setupBottomView()
        setupTableView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func setupStoryHeader(model : STStoryInfo, content : String) {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.white
        
        let titleLabel = UILabel()
        titleLabel.text = model.storyInfo.storyName
        titleLabel.textColor = UIColor.black
        titleLabel.font = .systemFont(ofSize: 21)
        titleLabel.numberOfLines = 1
        headerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(12)
            make.width.equalTo(UIScreen.main.bounds.size.width - 24)
            make.centerX.equalToSuperview()
            make.height.equalTo(25)
        }
        
        let avatarImageView = UIImageView()
        avatarImageView.layer.cornerRadius = 18
        avatarImageView.layer.masksToBounds = true
        avatarImageView.kf.setImage(with: URL(string: model.authorInfo.avatarUrl ?? ""), placeholder: UIImage.init(color: UIColor.init(white: 0, alpha: 0.1)))
        headerView.addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp_bottom).offset(18)
            make.left.equalToSuperview().offset(12)
            make.width.height.equalTo(36)
        }
        
        let authorNameLabel = UILabel()
        authorNameLabel.textColor = .black
        authorNameLabel.font = .systemFont(ofSize: 15)
        authorNameLabel.text = model.authorInfo.username
        headerView.addSubview(authorNameLabel)
        authorNameLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatarImageView)
            make.left.equalTo(avatarImageView.snp_right).offset(4)
        }
        
        let userAvatarBtn = UIButton()
        headerView.addSubview(userAvatarBtn)
        userAvatarBtn.snp.makeConstraints { (make) in
            make.left.top.bottom.equalTo(avatarImageView)
            make.right.equalTo(authorNameLabel)
        }
        userAvatarBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.delegate?.didClickUserAvatar(authorName: model.authorInfo.username)
        }).disposed(by: disposeBag)
        
        let followBtn = UIButton()
        followBtn.setTitle("关注", for: .normal)
        followBtn.setTitle("已关注", for: .selected)
        followBtn.backgroundColor = .red
        followBtn.layer.cornerRadius = 4
        headerView.addSubview(followBtn)
        followBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-18)
            make.centerY.equalTo(avatarImageView)
            make.size.equalTo(CGSize(width: 80, height: 30))
        }
        
        self.viewModel.followState.bind(to: followBtn.rx.isSelected).disposed(by: disposeBag)
        followBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.viewModel.changeFollowStatus()
        }).disposed(by: disposeBag)
        
        let storyAvatarImageView = UIImageView()
        if model.storyInfo.avatarUrl != nil {
            storyAvatarImageView.kf.setImage(with: URL(string: model.storyInfo.avatarUrl ?? ""), placeholder: UIImage.init(color: UIColor.init(white: 0, alpha: 0.1)))
            storyAvatarImageView.layer.cornerRadius = 4
            storyAvatarImageView.layer.masksToBounds = true
            storyAvatarImageView.contentMode = .scaleAspectFit
            headerView.addSubview(storyAvatarImageView)
            storyAvatarImageView.snp.makeConstraints { (make) in
                make.width.equalTo(UIScreen.main.bounds.size.width - 24)
                make.centerX.equalToSuperview()
                make.top.equalTo(avatarImageView.snp_bottom).offset(18)
                make.height.equalTo(storyAvatarImageView.snp_width).multipliedBy(9.0/16.0)
            }
        }
        
        let contentLabel = UILabel()
        contentLabel.text = content
        contentLabel.font = .systemFont(ofSize: 14)
        contentLabel.textColor = .gray
        contentLabel.numberOfLines = 0
        headerView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { (make) in
            make.width.equalTo(UIScreen.main.bounds.size.width - 24)
            if model.storyInfo.avatarUrl == nil {
                make.top.equalTo(avatarImageView.snp_bottom).offset(18)
            } else {
                make.top.equalTo(storyAvatarImageView.snp_bottom).offset(18)
            }
            make.centerX.equalToSuperview()
        }
        
        let line = UIView()
        line.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        headerView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.width.centerX.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(contentLabel.snp_bottom).offset(12)
        }
        
        let bottomLabel = UILabel()
        bottomLabel.text = "全部评论"
        bottomLabel.font = .systemFont(ofSize: 14)
        bottomLabel.textColor = .gray
        headerView.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { (make) in
            make.left.equalTo(contentLabel)
            make.top.equalTo(line.snp_bottom).offset(8)
            make.height.equalTo(15)
            make.bottom.equalToSuperview().offset(-12)
        }
        
        headerView.height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        
        tableView.beginUpdates()
        tableView.tableHeaderView = headerView
        tableView.endUpdates()
    }
    
    public func setupCommentHeader(model : STCommentInfo) {
        let headerView = UIView()
        headerView.backgroundColor = UIColor.white
        
        let avatarImageView = UIImageView()
        avatarImageView.layer.cornerRadius = 18
        avatarImageView.layer.masksToBounds = true
        avatarImageView.kf.setImage(with: URL(string: model.userInfo.avatarUrl ?? ""), placeholder: UIImage.init(color: UIColor.init(white: 0, alpha: 0.1)))
        headerView.addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(12)
            make.width.height.equalTo(36)
        }
        
        let authorNameLabel = UILabel()
        authorNameLabel.textColor = .black
        authorNameLabel.font = .systemFont(ofSize: 15)
        authorNameLabel.text = model.userInfo.username
        headerView.addSubview(authorNameLabel)
        authorNameLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatarImageView)
            make.left.equalTo(avatarImageView.snp_right).offset(4)
        }
        
        let userAvatarBtn = UIButton()
        headerView.addSubview(userAvatarBtn)
        userAvatarBtn.snp.makeConstraints { (make) in
            make.left.top.bottom.equalTo(avatarImageView)
            make.right.equalTo(authorNameLabel)
        }
        userAvatarBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.delegate?.didClickUserAvatar(authorName: model.userInfo.username)
        }).disposed(by: disposeBag)
        
        let contentLabel = UILabel()
        contentLabel.text = model.commentInfo.content
        contentLabel.font = .systemFont(ofSize: 14)
        contentLabel.textColor = .gray
        contentLabel.numberOfLines = 0
        headerView.addSubview(contentLabel)
        contentLabel.snp.makeConstraints { (make) in
            make.width.equalTo(UIScreen.main.bounds.size.width - 50)
            make.top.equalTo(avatarImageView.snp_bottom).offset(18)
            make.centerX.equalToSuperview()
        }
        
        let line = UIView()
        line.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        headerView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.width.centerX.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(contentLabel.snp_bottom).offset(12)
        }
        
        let bottomLabel = UILabel()
        bottomLabel.text = "全部回复"
        bottomLabel.font = .systemFont(ofSize: 14)
        bottomLabel.textColor = .gray
        headerView.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { (make) in
            make.left.equalTo(contentLabel)
            make.top.equalTo(line.snp_bottom).offset(8)
            make.height.equalTo(15)
            make.bottom.equalToSuperview().offset(-12)
        }
        
        headerView.height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        
        tableView.beginUpdates()
        tableView.tableHeaderView = headerView
        tableView.endUpdates()
    }
    
    private func setupTableView() {
        self.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-44)
        }
        self.viewModel.bindTableView(tableView: tableView)
        tableView.separatorStyle = .none
        tableView.rx.modelSelected(STCommentInfo.self).subscribe(onNext: { [weak self]
            commentInfo in
            self?.didClickComment(model: commentInfo)
        }).disposed(by: disposeBag)
    }
    
    private func setupBottomView() {
        bottomView.backgroundColor = UIColor.white
        self.addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        let line = UIView()
        line.backgroundColor = .init(white: 0, alpha: 0.3)
        bottomView.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        let collectBtn = UIButton()
        collectBtn.setImage(#imageLiteral(resourceName: "un_collected"), for: .normal)
        collectBtn.setImage(#imageLiteral(resourceName: "collected"), for: .selected)
        collectBtn.adjustsImageWhenHighlighted = false
        collectBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: {
            self.viewModel.changeCollectState()
        }).disposed(by: disposeBag)
        bottomView.addSubview(collectBtn)
        collectBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-18)
        }
        collectBtn.alpha = self.viewModel.isStory() ? 1 : 0
        self.viewModel.collectState.subscribe(onNext: { (state) in
            if collectBtn.isSelected == state {
                return
            }
            UIView.animate(withDuration: 0.1, animations: {
                collectBtn.transform = CGAffineTransform.init(scaleX: 0.1, y: 0.1)
            }, completion: { (finish) in
                collectBtn.isSelected = state
            })
            UIView.animate(withDuration: 0.1, delay: 0.1, options: .curveEaseInOut, animations: {
                collectBtn.transform = CGAffineTransform.identity
            }, completion: nil)
        }).disposed(by: disposeBag)
        
        let commentButton = UIButton()
        commentButton.layer.cornerRadius = 16
        commentButton.backgroundColor = .init(white: 0, alpha: 0.08)
        bottomView.addSubview(commentButton)
        commentButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(12)
            make.top.bottom.equalToSuperview().inset(6)
            if self.viewModel.isStory() {
                make.right.equalTo(collectBtn.snp_left).offset(-18)
            } else {
                make.right.equalToSuperview().offset(-12)
            }
        }
        
        commentInputView.placeholder = "说点什么吧..."
        commentInputView.textColor = .gray
        commentInputView.font = .systemFont(ofSize: 14)
        commentInputView.returnKeyType = .send
        commentInputView.delegate = self
        commentButton.addSubview(commentInputView)
        commentInputView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.right.equalToSuperview().inset(16)
        }
        
        self.addSubview(alphaButton)
        alphaButton.isUserInteractionEnabled = false
        alphaButton.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp_top)
        }
        alphaButton.rx.controlEvent(.touchDown).subscribe(onNext: { (_) in
            self.commentInputView.resignFirstResponder()
        }).disposed(by: disposeBag)
        
        NotificationCenter.default.rx.notification(UIView.keyboardWillShowNotification).subscribe(onNext: {[weak self] (notification) in
            if self == nil {
                return
            }
            self?.bringSubviewToFront(self!.alphaButton)
            self?.bringSubviewToFront(self!.bottomView)
            self?.alphaButton.isUserInteractionEnabled = true
            self?.commentInputView.text = self?.lastComment
            let keyboardinfo = notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey]
            let keyboardheight:CGFloat = (keyboardinfo as! NSValue).cgRectValue.size.height
            
            UIView.animate(withDuration: 0.25, animations: {
                self?.bottomView.snp.remakeConstraints({ (make) in
                    make.left.right.equalToSuperview()
                    make.height.equalTo(44)
                    make.bottom.equalToSuperview().offset(-keyboardheight)
                })
                self?.setNeedsLayout()
                self?.layoutIfNeeded()
            })
        }).disposed(by: disposeBag)
        NotificationCenter.default.rx.notification(UIView.keyboardWillHideNotification).subscribe(onNext: { (notification) in
            self.alphaButton.isUserInteractionEnabled = false
            UIView.animate(withDuration: 0.25, animations: {
                self.bottomView.snp.remakeConstraints { (make) in
                    make.bottom.left.right.equalToSuperview()
                    make.height.equalTo(44)
                }
                self.setNeedsLayout()
                self.layoutIfNeeded()
            })
            self.lastComment = self.commentInputView.text
            self.commentInputView.text = nil
        }).disposed(by: disposeBag)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.text == nil || textField.text == "" {
            HUD.flash(.label("评论内容不能为空"))
            return false
        }
        self.viewModel.sendComment(content: textField.text!)
        textField.text = nil
        textField.resignFirstResponder()
        return true
    }
    
    func didClickComment(model: STCommentInfo) {
        self.delegate?.didClickComment(model: model)
    }
}
